package com.atguigu.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.realtime.app.BaseAppV1;
import com.atguigu.realtime.bean.PlayChapter;
import com.atguigu.realtime.bean.TrafficPageViewBean;
import com.atguigu.realtime.common.Constant;
import com.atguigu.realtime.util.AtguiguUtil;
import com.atguigu.realtime.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.functions.RichReduceFunction;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.ArrayList;
import java.util.List;

/**
 * @auther yuzehua
 * @date 2022/10/26 - 13:53
 */
public class Dws_PlayChapter extends BaseAppV1 {
    public static void main(String[] args) {
        new Dws_PlayChapter().init(
                2011,
                2,
                "Dws_PlayChapter",
                Constant.TOPIC_DWD_PLAY_USER_CHAPTER_PROCESS
        );
    }
    @Override
    public void handle(StreamExecutionEnvironment env, DataStreamSource<String> stream) {
        // 1.封装到一个POJO中
        SingleOutputStreamOperator<PlayChapter> beanStream = parseToPojo(stream);
        // 2.开窗聚合
        SingleOutputStreamOperator<PlayChapter> resultStream = windowAndAgg(beanStream);
        resultStream.print();
        // 3. 写出到 clickhouse 中
        writeToClickhouse(resultStream);

    }

    private void writeToClickhouse(SingleOutputStreamOperator<PlayChapter> resultStream) {
        resultStream
                .addSink(FlinkSinkUtil.getClickHouseSink("dws_play_view_window",
                        PlayChapter.class
                ));
    }


    private SingleOutputStreamOperator<PlayChapter> windowAndAgg(SingleOutputStreamOperator<PlayChapter> beanStream) {
        return beanStream.assignTimestampsAndWatermarks(
                WatermarkStrategy
                        .<PlayChapter>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                        .withTimestampAssigner(new SerializableTimestampAssigner<PlayChapter>() {
                            @Override
                            public long extractTimestamp(PlayChapter element, long recordTimestamp) {
                                return element.getTs();
                            }
                        }))
                .keyBy(PlayChapter::getChapterId)
                .window(TumblingEventTimeWindows.of(Time.seconds(5)))
                .reduce(new ReduceFunction<PlayChapter>() {
                    @Override
                    public PlayChapter reduce(PlayChapter value1, PlayChapter value2) throws Exception {
                        List<String> list = new ArrayList<>();
                        list.add(value1.getUserId());
                        list.add(value2.getUserId());
                        value1.setSumPerson((long) list.size());
                        value1.setSumPositionSec(value1.getSumPositionSec() + value1.getSumPositionSec());
                        return value1;
                    }
                }, new ProcessWindowFunction<PlayChapter, PlayChapter, String, TimeWindow>() {
                    @Override
                    public void process(String s, Context ctx, Iterable<PlayChapter> elements, Collector<PlayChapter> out) throws Exception {
                        PlayChapter bean = elements.iterator().next();

                        Long sumPerson = bean.getSumPerson();
                        if (sumPerson != 0) {
                            bean.setAvgPersonView(bean.getSumPositionSec() / sumPerson);
                        } else {
                            bean.setSumPerson(1L);
                            bean.setAvgPersonView(bean.getSumPositionSec());
                        }
                        bean.setViewCount(bean.getSumPositionSec() / 30);
                        bean.setStt(AtguiguUtil.toDatTime(ctx.window().getStart()));
                        bean.setEdt(AtguiguUtil.toDatTime(ctx.window().getEnd()));

                        bean.setTs(System.currentTimeMillis());
                        out.collect(bean);
                    }
                });


    }

    private SingleOutputStreamOperator<PlayChapter> parseToPojo(DataStreamSource<String> stream) {
        return stream
                .map(JSON::parseObject)
                .map(new RichMapFunction<JSONObject, PlayChapter>() {

                    @Override
                    public PlayChapter map(JSONObject value) throws Exception {
                        String chapterId = value.getString("chapter_id");
                        String userId = value.getString("user_id");
                        Long SumPositionSec = value.getLong("position_sec");


                        Long ts = value.getLong("ts") * 1000;

                        return new PlayChapter("","",chapterId,userId,0L,SumPositionSec,
                                0L,0L,ts);
                    }
                });
    }
}
